<template>
  <view class="climber-edit-page">
    <!-- 页面标题 -->
    <view class="header">
      <text class="title">个人简介</text>
    </view>

    <view class="form-container">
      <uni-forms ref="form" :model="formData" :rules="rules">
        
        <!-- 基本信息 -->
        <view class="section">
          <!-- 姓名 -->
          <view class="form-item">
            <view class="label-row">
              <text class="label">姓名</text>
              <text class="required">*</text>
            </view>
            <view class="input-wrapper">
              <input 
                class="form-input" 
                v-model="formData.name" 
                placeholder="请输入真实姓名"
                maxlength="50"
              />
              <view v-if="formData.name" class="clear-btn" @tap="clearField('name')">×</view>
            </view>
          </view>
          
          <!-- 年龄 -->
          <view class="form-item">
            <view class="label-row">
              <text class="label">年龄</text>
            </view>
            <view class="input-wrapper">
              <input 
                class="form-input" 
                v-model="formData.age" 
                type="number"
                placeholder="请输入年龄"
                maxlength="3"
              />
              <text class="input-unit">岁</text>
            </view>
          </view>
          
          <!-- 性别 -->
          <view class="form-item">
            <view class="label-row">
              <text class="label">性别</text>
            </view>
            <view class="gender-wrapper">
              <view 
                class="gender-option" 
                :class="{ active: formData.sex === '0' }"
                @tap="selectGender('0')"
              >
                <text>男</text>
              </view>
              <view 
                class="gender-option" 
                :class="{ active: formData.sex === '1' }"
                @tap="selectGender('1')"
              >
                <text>女</text>
              </view>
              <view 
                class="gender-option" 
                :class="{ active: formData.sex === '2' }"
                @tap="selectGender('2')"
              >
                <text>未知</text>
              </view>
            </view>
          </view>
          
          <!-- 手机号 -->
          <view class="form-item">
            <view class="label-row">
              <text class="label">手机号</text>
            </view>
            <view class="input-wrapper">
              <input 
                class="form-input" 
                v-model="formData.phonenumber" 
                type="number"
                placeholder="请输入手机号"
                maxlength="11"
              />
              <view v-if="formData.phonenumber" class="clear-btn" @tap="clearField('phonenumber')">×</view>
            </view>
          </view>
          
          <!-- 个人简介文本 -->
          <view class="form-item">
            <view class="label-row">
              <text class="label">个人简介</text>
            </view>
            <view class="textarea-wrapper">
              <textarea 
                class="form-textarea" 
                v-model="formData.bio" 
                placeholder="请输入个人简介，让更多人了解您"
                maxlength="500"
              />
            </view>
          </view>
        </view>

      </uni-forms>

      <!-- 提交按钮 -->
      <view class="submit-area">
        <button 
          class="submit-btn" 
          @tap="submitForm" 
          :disabled="isSubmitting"
          :class="{ disabled: isSubmitting }"
        >
          <text v-if="isSubmitting">保存中...</text>
          <text v-else>保存资料</text>
        </button>
      </view>
    </view>
  </view>
</template>

<script>
import { getClimberInfo, updateClimberProfile, cleanClimberBio } from '@/api/climber'
import { getUserProfile, updateUserProfile } from '@/api/system/user'

export default {
  data() {
    return {
      // 表单数据 - 表示层
      formData: {
        name: '',           // 陪爬员姓名
        age: '',            // 年龄
        sex: '0',           // 性别 (0男1女2未知)
        phonenumber: '',    // 手机号
        bio: ''             // 个人简介
      },
      isSubmitting: false,
      rules: {
        name: {
          rules: [{
            required: true,
            errorMessage: '请输入真实姓名'
          }, {
            minLength: 2,
            maxLength: 50,
            errorMessage: '姓名长度应在2-50个字符之间'
          }]
        },
        phonenumber: {
          rules: [{
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            errorMessage: '请输入正确的手机号码'
          }]
        },
        age: {
          rules: [{
            pattern: /^[1-9]\d{0,2}$/,
            errorMessage: '请输入正确的年龄'
          }]
        }
      }
    }
  },
  onLoad() {
    this.loadUserData()
  },
  onReady() {
    this.$refs.form.setRules(this.rules)
  },
  methods: {
    // 数据加载 - 业务逻辑层
    async loadUserData() {
      try {
        this.$modal.loading('加载中...')
        
        // 并行获取陪爬员信息和用户信息
        const [climberResponse, userResponse] = await Promise.all([
          getClimberInfo(),
          getUserProfile()
        ])
        
        // 检查是否需要清理个人简介中的结构化数据
        await this.checkAndCleanBio(climberResponse)
        
        this.$modal.closeLoading()
        
        // 数据回显 - 表示层
        this.populateFormData(climberResponse, userResponse)
        
      } catch (error) {
        this.$modal.closeLoading()
        console.error('获取用户信息失败:', error)
        this.$modal.msgError('获取信息失败，请重试')
      }
    },
    
    // 检查并清理个人简介中的结构化数据 - 业务逻辑层
    async checkAndCleanBio(climberResponse) {
      if (climberResponse.code === 200 && climberResponse.data && climberResponse.data.bio) {
        const bioText = climberResponse.data.bio
        
        // 检查是否包含结构化数据
        const hasStructuredData = /姓名[：:]|年龄[：:]|性别[：:]|手机号[：:]|联系电话[：:]/.test(bioText)
        
        if (hasStructuredData) {
          try {
            // 调用后端清理接口
            await cleanClimberBio()
            console.log('已清理个人简介中的结构化数据')
          } catch (error) {
            console.warn('清理个人简介失败，使用前端清理:', error)
          }
        }
      }
    },
    
    // 数据回显 - 表示层
    populateFormData(climberResponse, userResponse) {
      // 优先使用陪爬员表中的数据，如果没有则使用用户表数据
      const climberData = climberResponse.code === 200 ? climberResponse.data : {}
      const userData = userResponse.code === 200 ? userResponse.data : {}
      
      // 提取纯粹的个人简介内容（去除结构化数据）
      const pureBio = this.extractPureBio(climberData.bio || '')
      
      this.formData = {
        name: climberData.name || userData.nickName || '',
        age: climberData.age || '',
        sex: climberData.sex || userData.sex || '0',
        phonenumber: climberData.phonenumber || userData.phonenumber || '',
        bio: pureBio  // 只显示纯粹的个人简介内容
      }
    },
    
    // 提取纯粹的个人简介内容 - 业务逻辑层
    extractPureBio(bioText) {
      if (!bioText) return ''
      
      // 移除结构化数据，只保留纯粹的个人简介内容
      let pureBio = bioText
      
      // 移除姓名信息
      pureBio = pureBio.replace(/姓名[：:][^\n]*\n?/g, '')
      
      // 移除年龄信息
      pureBio = pureBio.replace(/年龄[：:][^\n]*\n?/g, '')
      
      // 移除性别信息
      pureBio = pureBio.replace(/性别[：:][^\n]*\n?/g, '')
      
      // 移除手机号信息
      pureBio = pureBio.replace(/(?:手机号|联系电话)[：:][^\n]*\n?/g, '')
      
      // 清理多余的空行和空白字符
      pureBio = pureBio.replace(/\n\s*\n/g, '\n').trim()
      
      return pureBio
    },
    
    // 清空输入框 - 表示层
    clearField(fieldName) {
      this.formData[fieldName] = ''
    },
    
    // 选择性别 - 表示层
    selectGender(genderCode) {
      this.formData.sex = genderCode
    },
    
    // 表单验证 - 业务逻辑层
    validateForm() {
      if (!this.formData.name.trim()) {
        this.$modal.msgError('请输入真实姓名')
        return false
      }
      
      if (this.formData.phonenumber && !/^1[3|4|5|6|7|8|9][0-9]\d{8}$/.test(this.formData.phonenumber)) {
        this.$modal.msgError('请输入正确的手机号码')
        return false
      }
      
      if (this.formData.age && !/^[1-9]\d{0,2}$/.test(this.formData.age)) {
        this.$modal.msgError('请输入正确的年龄')
        return false
      }
      
      return true
    },
    
    // 数据保存 - 业务逻辑层
    async submitForm() {
      try {
        // 表单验证
        const valid = await this.$refs.form.validate()
        if (!valid || !this.validateForm()) {
          return
        }
        
        this.isSubmitting = true
        
        // 准备更新数据
        const updateData = this.prepareUpdateData()
        
        // 分别更新陪爬员信息和用户信息
        await this.updateUserData(updateData)
        
        this.$modal.msgSuccess('保存成功')
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
        
      } catch (error) {
        console.error('保存失败:', error)
        this.$modal.msgError('保存失败，请重试')
      } finally {
        this.isSubmitting = false
      }
    },
    
    // 准备更新数据 - 业务逻辑层
    prepareUpdateData() {
      // 转换性别格式：0->男, 1->女, 2->未知
      let gender = '未知'
      if (this.formData.sex === '0') {
        gender = '男'
      } else if (this.formData.sex === '1') {
        gender = '女'
      }
      
      return {
        name: this.formData.name.trim(),
        age: this.formData.age ? parseInt(this.formData.age) : null,
        gender: gender,
        phone: this.formData.phonenumber || null,
        bio: this.formData.bio.trim() || null
      }
    },
    
    // 更新用户数据 - 数据访问层
    async updateUserData(updateData) {
      // 直接调用陪爬员profile更新接口，后端会同时更新陪爬员表和用户表
      const response = await updateClimberProfile(updateData)
      
      if (response.code !== 200) {
        throw new Error(response.msg || '更新失败')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.climber-edit-page {
  min-height: 100vh;
  background: #f5f6f7;
}

.header {
  background: #fff;
  padding: 32rpx;
  text-align: center;
  border-bottom: 1rpx solid #f0f0f0;
}

.title {
  font-size: 36rpx;
  font-weight: 700;
  color: #333;
}

.form-container {
  padding: 32rpx;
}

.section {
  background: #fff;
  border-radius: 16rpx;
  padding: 32rpx;
  margin-bottom: 24rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: 700;
  color: #333;
  display: block;
  margin-bottom: 32rpx;
}

// 表单项样式
.form-item {
  margin-bottom: 32rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.label-row {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;
}

.label {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

.required {
  color: #ff4757;
  font-size: 24rpx;
  margin-left: 4rpx;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.form-input {
  width: 100%;
  height: 80rpx;
  padding: 0 24rpx;
  border: 1rpx solid #e5e5e5;
  border-radius: 12rpx;
  font-size: 28rpx;
  color: #333;
  background: #fff;
  
  &:focus {
    border-color: #1989fa;
  }
  
  &:disabled {
    background: #f5f5f5;
    color: #999;
    border-color: #ddd;
  }
}

.clear-btn {
  position: absolute;
  right: 20rpx;
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  background: #ddd;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
  font-weight: bold;
}

.input-unit {
  position: absolute;
  right: 24rpx;
  color: #999;
  font-size: 24rpx;
}

// 性别选择器样式
.gender-wrapper {
  display: flex;
  gap: 16rpx;
}

.gender-option {
  flex: 1;
  height: 80rpx;
  border: 1rpx solid #e5e5e5;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  color: #666;
  background: #fff;
  transition: all 0.3s;
  
  &.active {
    border-color: #1989fa;
    background: #f0f8ff;
    color: #1989fa;
    font-weight: 600;
  }
  
  &[disabled] {
    background: #f5f5f5;
    color: #ccc;
  }
}

.textarea-wrapper {
  width: 100%;
}

.form-textarea {
  width: 100%;
  min-height: 120rpx;
  padding: 24rpx;
  border: 1rpx solid #e5e5e5;
  border-radius: 12rpx;
  font-size: 28rpx;
  color: #333;
  background: #fff;
  resize: none;
  
  &:focus {
    border-color: #1989fa;
  }
  
  &:disabled {
    background: #f5f5f5;
    color: #999;
    border-color: #ddd;
  }
}

// 只读显示样式
.bio-display {
  padding: 24rpx;
  background: #f8f9fa;
  border-radius: 12rpx;
  border: 1rpx solid #e5e5e5;
}

.bio-text {
  font-size: 26rpx;
  color: #666;
  line-height: 1.6;
}


// 提交按钮样式
.submit-area {
  padding: 40rpx 32rpx;
}

.submit-btn {
  width: 100%;
  height: 88rpx;
  background: #1989fa;
  color: #fff;
  border: none;
  border-radius: 16rpx;
  font-size: 32rpx;
  font-weight: 600;
  
  &.disabled {
    background: #ccc;
    color: #999;
  }
}
</style>
